import { defineStore } from "pinia";
import user from "@/api/user";
import type { typeUserInfo } from "@/api/user";
// 持久化存储
import _ from "@/utils/local";

interface stateType {
  token: string;
  userInfo: typeUserInfo;
}
// 初始化数据
const reset = () => {
  return {
    token: _.getItem() || "",
    userInfo: {
      _id: "",
      username: "",
      email: "",
      photo: "",
      createdAt: "",
    },
  };
};

export const useUserStore = defineStore("user", {
  state: (): stateType => {
    return reset();
  },
  actions: {
    // 登录
    async getLogin(payload: { email: string; password: string }) {
      const re = await user.reqeustLogin(payload);
      this.token = re.token;
      _.setItem(re.token);
    },
    // 用户信息
    async getUserInfo() {
      const re = await user.reqeustUserInfo();
      this.userInfo = re;
    },
    reset() {
      _.removeItem();
      this.$state = reset();
    },
    //注册
    async getRegister(payload: { username: string, phone: string, email: string, password: string }) {
      const re = await user.reqeustRegister(payload);
      // this.token = re.token
      // _.setItem(re.token)
    },
  },
  getters: {},
});
